//
//  FirstViewController.m
//  WeatherCast
//
//  Created by anlong on 14/11/15.
//  Copyright (c) 2014年 anlong. All rights reserved.
//

#import "FirstViewController.h"

#import <MapKit/MKReverseGeocoder.h>
#import <MapKit/MKPlacemark.h>
#import "SBJSON.h"
#import "WeatherInfo.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

@synthesize citysInfo;
@synthesize arrayWeatherInfo;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"西安",@"武汉", nil];
    
    self.listData = array;
    
    _locationManager = [[CLLocationManager alloc] init];
    
    _locationManager.delegate = self;
    
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    _locationManager.distanceFilter = 1000.0f;
    
    self.citysInfo = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, 320, 400) style:UITableViewStylePlain];
    
    self.citysInfo.delegate = self;//设置代理为自身
    self.citysInfo.dataSource = self;//设置数据源为自身
    self.citysInfo.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;//确保TablView能够正确的调整大小
    
    // 向主视图中添加bar和list
    [self.view addSubview:self.naviagteBar];
    [self.view addSubview:self.citysInfo];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    //开始定位
    //[_locationManager startUpdatingLocation];
    
    // request weather
    [self RequestWeatherInfo:self.listData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    //停止定位
    
    [_locationManager stopUpdatingLocation];
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation * currLocation = [locations lastObject];
    
    _txtLat.text = [NSString stringWithFormat:@"%3.5f",
                    
                    currLocation.coordinate.latitude];
    
    _txtLng.text = [NSString stringWithFormat:@"%3.5f",
                    
                    currLocation.coordinate.longitude];
    
    _txtAlt.text = [NSString stringWithFormat:@"%3.5f",
                    
                    currLocation.altitude];
    
  
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
                        NSDictionary *test = [placemark addressDictionary];
                        //  Country(国家)  State(城市)  SubLocality(区)
                        NSLog(@"%@", [test objectForKey:@"Country"]);
                        NSLog(@"%@", [test objectForKey:@"State"]);
                        NSLog(@"%@", [test objectForKey:@"SubLocality"]);
                    }
        
        if (error == nil &&[placemarks count] > 0){
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            /* We received the results */
            NSLog(@"Country = %@", placemark.country);
            NSLog(@"Postal Code = %@", placemark.postalCode);
            NSLog(@"Locality = %@", placemark.locality);
            NSLog(@"dic = %@", placemark.addressDictionary );
            NSLog(@"dic FormattedAddressLines= %@", [placemark.addressDictionary objectForKey:@"FormattedAddressLines"]);
            NSLog(@"dic Name = %@", [placemark.addressDictionary objectForKey:@"Name"]);
            NSLog(@"dic State = %@", [placemark.addressDictionary objectForKey:@"State"]);
            NSLog(@"dic Street = %@", [placemark.addressDictionary objectForKey:@"Street"]);
            NSLog(@"dic SubLocality= %@", [placemark.addressDictionary objectForKey:@"SubLocality"]);
            NSLog(@"dic SubThoroughfare= %@", [placemark.addressDictionary objectForKey:@"SubThoroughfare"]);
            NSLog(@"dic Thoroughfare = %@", [placemark.addressDictionary objectForKey:@"Thoroughfare"]);
            
            [_curPosition setText:[placemark.addressDictionary objectForKey:@"Name"]];
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error: %@",error);
}

-(void)clickAddCityButton
{
    NSLog(@"clickAddCityButton");
    [self.listData addObject:@"兰州"];
    [citysInfo reloadData];
    
    [self RequestWeatherInfo:self.listData];
}

-(void)clickEditCityButton
{
    NSLog(@"clickEditCityButton");
    if( NO == [self.citysInfo isEditing] ){
        [self.citysInfo setEditing:YES animated:YES];
    }else{
        [self.citysInfo setEditing:NO animated:YES];
    }
}


//设置每行的高度
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat result = 80.0f;
    if ([tableView isEqual:self.citysInfo]) {
        result = 80.0f;
    }
    return result;
}
//允许数据源告知必须加载到Table View中的表的Section数。
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSInteger result = 1;
    if([tableView isEqual:self.citysInfo]){
        result = 1;//一共三个section
    }
    return result;
}
//设置每个Section呈现多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger result = 0;
    if ([tableView isEqual:self.citysInfo]) {
        return [self.listData count];
    }
    return result;
}
//每行像是的数据
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *result = nil;
    if ([tableView isEqual:self.citysInfo]) {
        static NSString *tableViewCellIdentifier = @"MyCells";//设置Cell标识
        result = [tableView dequeueReusableCellWithIdentifier:tableViewCellIdentifier];//通过标示符返回一个可重用的表视图单元格对象
        if (result == nil) {
            result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableViewCellIdentifier];//初始化一个表格单元格样式和重用的标识符,并将它返回给调用者。
        }
        //indexPath.section 表示section的索引 indexPath.row表示行数的索引
        NSLog(@"indexPath section:%ld", (long)[indexPath row]);
        
        result.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        result.textLabel.text = [self.listData objectAtIndex:[indexPath row]];
       
        //result.detailTextLabel.text = @"晴转多云 0～20摄氏度 东北风 建议多穿衣服 ";
        
        result.textLabel.font = [UIFont boldSystemFontOfSize:20.0f];
        
        result.textLabel.backgroundColor=[UIColor clearColor];
        
        if ( arrayWeatherInfo ) {
            for (NSInteger i = 0; i < [arrayWeatherInfo count]; i ++ ) {
                
                WeatherInfo* infos = [arrayWeatherInfo objectAtIndex:i];
                
                if( 0 == [[self.listData objectAtIndex:[indexPath row]] compare: infos.city] ){
                    
//                    for( NSInteger j = 0; j < [infos.weatherDatas count]; j ++ ){
//                        weatherData* data = [infos.weatherDatas objectAtIndex:j];
//                        
//                        NSString* brief = [[NSString alloc] initWithFormat:@"%@ %@ %@", data.weather, data.wind, data.temperature];
//                        result.detailTextLabel.text = brief;
//                    }
                    if( [infos.weatherDatas count] > 0 ){
                        weatherData* data = [infos.weatherDatas objectAtIndex:0];
                        NSString* brief = [[NSString alloc] initWithFormat:@"%@ %@ %@", data.weather, data.wind, data.temperature];
                        result.detailTextLabel.text = brief;
                    }
                }
            }
        }
    }
    
    return result;
}
//点击某一行时候触发的事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.citysInfo]) {
//        NSLog(@"%@",[NSString stringWithFormat:@"Cell %ld in Section %ld is selected",(long)indexPath.row,(long)indexPath.section]);
    }
}

-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    //    需要的移动行
    NSInteger fromRow = [sourceIndexPath row];
    //    获取移动某处的位置
    NSInteger toRow = [destinationIndexPath row];
    //    从数组中读取需要移动行的数据
    id object = [self.listData objectAtIndex:fromRow];
    //    在数组中移动需要移动的行的数据
    [self.listData removeObjectAtIndex:fromRow];
    //    把需要移动的单元格数据在数组中，移动到想要移动的数据前面
    [self.listData insertObject:object atIndex:toRow];
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        //        获取选中删除行索引值
        NSInteger row = [indexPath row];
        //        通过获取的索引值删除数组中的值
        [self.listData removeObjectAtIndex:row];
        //        删除单元格的某一行时，在用动画效果实现删除过程
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}


-(void)RequestWeatherInfo:(NSArray*)citysName
{
    NSString* strCitys = [[NSString alloc]init];
    for ( NSInteger i = 0; i < [citysName count]; i ++ ) {
        strCitys = [strCitys  stringByAppendingString: [citysName objectAtIndex:i]];
        if( i < ([citysName count] - 1 )){
           strCitys = [strCitys  stringByAppendingString: @"|"];
        }
    }
    
    NSString * strUrl = [NSString stringWithFormat:@"http://api.map.baidu.com/telematics/v3/weather?location=%@&output=json&ak=vprRmjakEGo0ONk5kAVo5Gie&mcode=long.Weather", strCitys ];
    
    NSString * newUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString : newUrl];
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //获取一个主队列
    NSOperationQueue *queue=[NSOperationQueue mainQueue];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        NSError* error = nil;
        if(data){
            NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
            // find whose data
            NSMutableArray* array;
            
            [self parseWeatherJson:data outputInfo:&array error:&error];
            
            arrayWeatherInfo = array;
            
            [citysInfo reloadData];
        }
    }];
}

-(void)parseWeatherJson:(NSData*)data outputInfo:(NSMutableArray**) arrayCitysInfo error:(NSError**) error{
    
    *arrayCitysInfo = [[NSMutableArray alloc]init];
    
    NSString* jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
    
    id jsonObjects = [jsonParser objectWithString:jsonString];
    
    if ([jsonObjects isKindOfClass:[NSDictionary class]]){
        NSDictionary *rootDic = [jsonParser objectWithString:jsonString error:error];
        
        id reqError= [rootDic objectForKey:@"error"];
//        if( [reqError isEqual:0] == NO ){
//            
//            // TODO notify ui
//            return;
//        }
     
        NSArray* reslutArray = [rootDic objectForKey:@"results"];
        NSDictionary *infoDic =  nil;
        
        for (NSUInteger i = 0; i < [reslutArray count]; i ++) {
            
            WeatherInfo* weatherInfo = [[WeatherInfo alloc]init];
            weatherInfo.weatherDatas = [[NSMutableArray alloc]init];
            
            infoDic = [reslutArray objectAtIndex:i];
            
            weatherInfo.city = [[NSString alloc]initWithFormat:@"%@", [infoDic objectForKey:@"currentCity"]];
            weatherInfo.pm25 = [[NSString alloc]initWithFormat:@"%@",[infoDic objectForKey:@"pm25"]];
            
            NSArray* arrayWeather_data = [infoDic objectForKey:@"weather_data"];
            
            for (NSInteger j = 0;  j < [arrayWeather_data count]; j ++ ) {
                
                NSDictionary* weather = [arrayWeather_data objectAtIndex:j];
                weatherData* data = [[weatherData alloc]init];
                
                data.date = [[NSString alloc]initWithFormat:@"%@", [weather objectForKey:@"date"]];
                data.weather = [[NSString alloc]initWithFormat:@"%@", [weather objectForKey:@"weather"]];
                data.wind = [[NSString alloc]initWithFormat:@"%@", [weather objectForKey:@"wind"]];
                data.temperature = [[NSString alloc]initWithFormat:@"%@", [weather objectForKey:@"temperature"]];
                
                [ weatherInfo.weatherDatas addObject:data ];
            }
            
            [*arrayCitysInfo addObject:weatherInfo];
        }
    }
    else{
        
    }
}

-(void) syncDataToUI{
    [citysInfo reloadData];
}
//下载开始函下

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response{
    
}

//下载中的函数

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"%s",__FUNCTION__);
}

//完成加载的函数

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    //将下载完成的数据转换成string类型的
    //NSString *responseStr = [[NSString alloc] initWithData:self.receivedDataencoding:NSUTF8StringEncoding];
}

@end
